#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
#include "kernel/fcntl.h"
#include "kernel/fs.h"

#define MAX_PATH_LEN 512

int main(void) {
    char path[MAX_PATH_LEN] = {0};
    char name[DIRSIZ + 1];
    struct stat st, pst;
        char temp[MAX_PATH_LEN];
//	int num = 0;

    // 打开当前目录
    int fd = open(".", O_RDONLY);
    if (fd < 0) {
        printf("pwd: cannot open .\n");
        exit(1);
    }

    // 获取当前目录信息
    if (fstat(fd, &st) < 0) {
        printf("pwd: cannot stat .\n");
        close(fd);
        exit(1);
    }
    close(fd);

    while (1) {
        // 打开父目录
        int pfd = open("..", O_RDONLY);
        if (pfd < 0) {
            printf("pwd: cannot open ..\n");
            exit(1);
        }

        // 获取父目录信息
        if (fstat(pfd, &pst) < 0) {
            printf("pwd: cannot stat ..\n");
            close(pfd);
            exit(1);
        }


        // 判断是否到达根目录
        if (st.ino == pst.ino) {
//		printf("pwd:dao da gen mu lu\n");
            close(pfd);
            break;
        }

        // 查找当前目录在父目录中的名称
        struct dirent de;
        int found = 0;
        while (read(pfd, &de, sizeof(de)) == sizeof(de)) {
            if (de.inum == (ushort)st.ino) {
                memmove(name, de.name, DIRSIZ);
                name[DIRSIZ] = '\0';
                found = 1;
                break;
            }
        }

        if (!found) {
            printf("pwd: entry not found\n");
            close(pfd);
            exit(1);
        }

        // 构建路径
        //snprintf(temp, sizeof(temp), "/%s%s", name, path);
        //strncpy(path, temp, sizeof(path));

	memset(temp, 0, sizeof(temp));
	temp[0] = '/';
	memmove(temp + 1, name, strlen(name));
	memmove(temp + 1 + strlen(name), path, strlen(path));
	memmove(path, temp, sizeof(temp));
	//num++;
//	printf("%d\n",num);
//	printf("%s\n",path);

        st = pst; // 更新为父目录信息
	chdir("..");
        close(pfd);
    }

    printf("%s\n", path[0] ? path : "/");
    exit(0);
}
